package cc.eddic.practice.spring.webapi;

import cc.eddic.practice.spring.domain.Category;
import cc.eddic.practice.spring.domain.Option;
import cc.eddic.practice.spring.domain.Question;
import cc.eddic.practice.spring.domain.SubCategory;
import cc.eddic.practice.spring.dto.*;
import cc.eddic.practice.spring.repository.CategoryRepository;
import cc.eddic.practice.spring.repository.QuestionRepository;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import java.net.URI;
import java.util.NoSuchElementException;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/api/questions")
public class QuestionRestController {

    public QuestionRestController(QuestionRepository repository) {
        this.repository = repository;
    }

    @PostMapping
    public HttpEntity<?> add(@RequestBody final QuestionAddRequest model) {
        log.debug("接收到model: {}", model);
        val question = repository.save(model.as());
        log.debug("Category saved with ID: {}", question.getId());
        return ResponseEntity.created(ServletUriComponentsBuilder.fromCurrentRequest()
                .path("/{id}").buildAndExpand(question.getId()).toUri()).build();
    }


    @GetMapping("/{id}")
    public HttpEntity<QuestionResponse> get(@PathVariable("id") final long id) {
        if (log.isDebugEnabled()) log.debug("id = {}", id);
        val question = repository.findById(id).orElseThrow(NoSuchElementException::new);
        return ResponseEntity.ok(QuestionResponse.from(question));
    }

    @PostMapping("/{questionId}/options")
    public HttpEntity<?> add(@PathVariable("questionId") Long questionId, @RequestBody final OptionAddRequest model){
        try {
            Question question = repository.findById(questionId)
                    .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "question not found"));

            Option option = model.as();
            question.add(option);
            repository.save(question);

            URI location = ServletUriComponentsBuilder.fromCurrentRequest()
                    .path("/{optionId}")
                    .buildAndExpand(question, option.getId())
                    .toUri();

            return ResponseEntity.created(location).build();
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to add option");
        }
    }



    @GetMapping("/{questionId}/questions")
    public HttpEntity<?> get(@PathVariable("questionId") Long questionId){
        if (log.isDebugEnabled())log.debug("questionId = {}",questionId);
        val question = repository.findById(questionId).orElseThrow(NoSuchElementException::new);
        if (log.isDebugEnabled())log.debug("run lazy load");
        return ResponseEntity.ok(question.getOptions().stream().map(OptionResponse::from).collect(Collectors.toList()));
    }




    @GetMapping("/{questionId}/options/{optionId}")
    public HttpEntity<?> get(@PathVariable("questionId") Long questionId, @PathVariable("optionId") Long optionId){
        if (log.isDebugEnabled())log.debug("questionId = {}, subCategoryId = {}", questionId, optionId);
        Question question = repository.findById(questionId).orElseThrow(NoSuchElementException::new);
        val option = question.getOptions().stream()
                .filter(option1 -> option1.getId()
                        .equals(optionId)).findFirst()
                .orElseThrow(NoSuchElementException::new);

        return ResponseEntity.ok(OptionResponse.from(option));
    }


    private final QuestionRepository repository;



}
